package com.learn.sb.activemq.configuration;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class JmsTemplateConfiguration {
    @Autowired
    Environment env;

    @Bean
    public ConnectionFactory connectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
                env.getProperty("spring.activemq.user"),
                env.getProperty("spring.activemq.password"),
                env.getProperty("spring.activemq.broker-url")
        );
        // 不设置无法 传输对象
        List<String> trustedPkglist = new ArrayList<String>();
        trustedPkglist.add("com.learn.sb.activemq.pojo");
        trustedPkglist.add("java.lang");
        activeMQConnectionFactory.setTrustedPackages(trustedPkglist);

        PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory);
        pooledConnectionFactory.setMaxConnections(
                Integer.parseInt(env.getProperty("spring.activemq.pool.max-connections"))
        );

        return pooledConnectionFactory;
    }

    @Bean
    public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
        String destination = env.getProperty("spring.jms.template.default-destination");
        jmsTemplate.setDefaultDestinationName(destination);
        jmsTemplate.setPubSubDomain(true); // 不设置无法接受消息
        jmsTemplate.setPriority(99);

        return jmsTemplate;
    }

}
